/*
 * sw_spi.h
 *
 *  Created on: Dec 22, 2018
 *      Author: zhan
 */

#ifndef HARDWARE_SW_SPI_H_
#define HARDWARE_SW_SPI_H_

#include "stm32f4xx.h"
#include "hardware/gpio_pin.h"
#include "spi_if.h"

class SoftwareSpi : public SpiInterface{
protected:
	GpioPin *cs;
	GpioPin *clk;
	GpioPin *miso;
	GpioPin *mosi;

	void init(){
		this->cs->set_output(Bit_SET);
		this->clk->set_output(Bit_SET);
		this->miso->set_input();
		this->mosi->set_output(Bit_SET);
	}

public:
	SoftwareSpi(GpioPin *cs, GpioPin *clk, GpioPin *miso, GpioPin *mosi) : SpiInterface(){
		this->cs = cs;
		this->clk = clk;
		this->miso = miso;
		this->mosi = mosi;
		init();
	}

	~SoftwareSpi(){

	}

	uint8_t read_write(uint8_t data){
		uint8_t rdata = 0;
		clk->write(Bit_RESET);
		for(int i=0;i<8;i++){
			if ( data & (0x80>>i) ){
				mosi->write(Bit_SET);
			}else{
				mosi->write(Bit_RESET);
			}
			clk->write(Bit_SET);
			if ( miso->read() == Bit_SET ){
				rdata |= 0x80>>i;
			}
			clk->write(Bit_RESET);
		}
		return rdata;
	}

	void enable_chip(){
		cs->write(Bit_RESET);
	}

	void disable_chip(){
		cs->write(Bit_SET);
	}

};


#endif /* HARDWARE_SW_SPI_H_ */
